package com.my.sys.service.impl;

import com.my.app.http.PageResult;
import com.my.sys.model.SysResource;
import com.my.sys.repository.SysResourceRepository;
import com.my.sys.service.SysResourceService;
import com.my.utils.PageUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 80002023 on 2016/5/11.
 */
@Service
public class SysResourceServiceImpl implements SysResourceService {

    private final Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private SysResourceRepository sysResourceRepository;

    public SysResource saveOrUpdate(SysResource record) {
        return sysResourceRepository.save(record);
    }

    public List<SysResource> saveOrUpdate(List<SysResource> records) {
        return sysResourceRepository.save(records);
    }


    public void delete(SysResource record) {
        sysResourceRepository.delete(record);
    }

    public SysResource find(Long id) {
        return sysResourceRepository.findOne(id);
    }

    public List<SysResource> find(SysResource record) {
        return null;
    }

    public void delete(Long id) {
        sysResourceRepository.delete(id);
    }

    public List<SysResource> findAll() {
        return sysResourceRepository.findAll();
    }

    public PageResult<SysResource> findPage(SysResource record, int pageNum, int pageSize) {
        if (record == null) {
            record = new SysResource();
        }
        Example<SysResource> example = Example.of(record);
        Pageable pageable = new PageRequest(PageUtils.convertPageOfZero(pageNum), pageSize);
        Page<SysResource> page = sysResourceRepository.findAll(example, pageable);
        logger.info("total page && size {}:{}", page.getTotalPages(), page.getSize());
        logger.info("number&number of elements {}:{}", page.getNumber(), page.getNumberOfElements());
        return new PageResult<SysResource>(page, pageNum, pageSize);
    }

    public List<SysResource> findNav() {
        SysResource record = new SysResource();
        record.setType("0");
        Example<SysResource> example = Example.of(record);
        List<SysResource> nav = sysResourceRepository.findAll(example);
        for (SysResource resource : nav) {
            record.setType("1");
            record.setParentId(resource.getId());
            example = Example.of(record);
            List<SysResource> children = sysResourceRepository.findAll(example);
            resource.setChildren(children);
        }
        return nav;
    }
}
